package com.wjh.yygh.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjh.yygh.common.exception.YyghException;
import com.wjh.yygh.common.result.ResultCodeEnum;
import com.wjh.yygh.enums.AuthStatusEnum;
import com.wjh.yygh.helper.JwtHelper;
import com.wjh.yygh.model.user.Patient;
import com.wjh.yygh.model.user.UserInfo;
import com.wjh.yygh.user.service.PatientService;
import com.wjh.yygh.user.service.UserInfoService;
import com.wjh.yygh.user.mapper.UserInfoMapper;
import com.wjh.yygh.vo.user.LoginVo;
import com.wjh.yygh.vo.user.UserAuthVo;
import com.wjh.yygh.vo.user.UserInfoQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wangjunhong
 * @description 针对表【user_info(用户表)】的数据库操作Service实现
 * @createDate 2022-08-09 09:46:14
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
        implements UserInfoService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private PatientService patientService;

    @Override
    public Map<String, Object> loginInfo(LoginVo loginVo) {
        //获取手机号和验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
//        验证手机和验证码是否为空
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        //验证手机号和验证码是否一致
        String redisCode = redisTemplate.opsForValue().get(phone);
        if (code.equals(redisCode)) {
            throw new YyghException(ResultCodeEnum.CODE_ERROR);
        }
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.eq("phone", phone);
        UserInfo userInfo = baseMapper.selectOne(userInfoQueryWrapper);
        if (StringUtils.isEmpty(userInfo)) {
            userInfo = new UserInfo();
            userInfo.setName(null);
            userInfo.setPhone(phone);
            userInfo.setStatus(1);
            baseMapper.insert(userInfo);
        }
        if (userInfo.getStatus() == 0) {
            throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
//        验证是否第一次登录
        HashMap<String, Object> map = new HashMap<>();

        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
//        生成token
        map.put("token", JwtHelper.createToken(userInfo.getId(), userInfo.getName()));
        return map;
    }

    /**
     * 用户认证
     *
     * @param userId
     * @param userAuthVo
     */
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        UserInfo userInfo = baseMapper.selectById(userId);
        userInfo.setName(userAuthVo.getName());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        baseMapper.updateById(userInfo);
    }

    /**
     * 用户列表条件查找
     *
     * @param userInfoPage
     * @param userInfoQueryVo
     * @return
     */
    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> userInfoPage, UserInfoQueryVo userInfoQueryVo) {
        String keyword = userInfoQueryVo.getKeyword();//用户名
        Integer status = userInfoQueryVo.getStatus(); //状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin(); //开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();  //结束时间
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(keyword)) {
            userInfoQueryWrapper.like("name", keyword);
        }
        if (!StringUtils.isEmpty(status)) {
            userInfoQueryWrapper.eq("status", status);
        }
        if (!StringUtils.isEmpty(createTimeBegin)) {
            userInfoQueryWrapper.ge("create_time", createTimeBegin);
        }
        if (!StringUtils.isEmpty(createTimeEnd)) {
            userInfoQueryWrapper.le("create_time", createTimeEnd);
        }
        Page<UserInfo> userInfoPage1 = baseMapper.selectPage(userInfoPage, userInfoQueryWrapper);
        userInfoPage1.getRecords().stream().forEach(userInfo -> {
            this.packageUserInfo(userInfo);
        });
        return userInfoPage1;
    }

    @Override
    public boolean lock(Long id, Integer status) {
        UserInfo userInfo = baseMapper.selectById(id);
        userInfo.setStatus(status);
        return baseMapper.updateById(userInfo) > 0;
    }

    /**
     * 用户详情页
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> show(Long id) {

        LinkedHashMap<String, Object> result = new LinkedHashMap<>();
        UserInfo userInfo = baseMapper.selectById(id);
        this.packageUserInfo(userInfo);
        result.put("userInfo",userInfo);
        List<Patient> patientList =  patientService.findAllByUserId(userInfo.getId());
        result.put("patientList",patientList);
        return result;
    }

    /**
     * 认证审批
     * @param id
     * @param authStatus
     */
    @Override
    public void approval(Long id, Integer authStatus) {
        if (authStatus.intValue()!=2 || authStatus.intValue()==-1){
            UserInfo userInfo = baseMapper.selectById(id);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }

    /**
     *
     * @param userInfo
     * @return
     */
    private UserInfo packageUserInfo(UserInfo userInfo) {
        userInfo.getParam().put("authStatusSting", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        String statusString = userInfo.getStatus().intValue() == 0 ? "锁定" : "正常";
        userInfo.getParam().put("statusString", statusString);
        return userInfo;
    }




}




